<script setup>
import { ref, onMounted } from 'vue';
import { queryBrand, addBrand, selectBrandById, updateBrand, deleteBrandById } from '@/api/brand';
import { ElMessage, ElMessageBox } from 'element-plus';

// 表格数据
const BrandData = ref([]);
// 表单数据
const formData = ref({
  name: '',
  createBy: ''
});
// 分页数据定义
const queryForm = ref({
  page: 1,
  pageSize: 5,
  total: 0,
  pages: 1,
});
// 弹窗相关
const dialogVisible = ref(false);
const dialogTitle = ref('新增品牌');
const form = ref({
  id: '',
  name: '',
  sort: 0,
  createBy: '',
  updateBy: ''
});

// 加载品牌数据（分页查询）
const queryBrands = async () => {
  try {
    const params = {
      ...queryForm.value,
      ...formData.value
    }
    const result = await queryBrand(params);
    console.log(result)
    if (result && result.data) {
      BrandData.value = result.data.list;
      queryForm.value.pages = result.pages || 1;
      queryForm.value.total = result.data.total || 0;
    } else {
      BrandData.value = [];
      queryForm.value.pages = 1;
      queryForm.value.total = 0;
      ElMessage.warning('未获取到品牌数据');
    }
  } catch (error) {
    console.error('查询品牌数据失败:', error);
    ElMessage.error('查询品牌数据失败，请稍后重试');
  }
}

// 页面大小变化
const handleSizeChange = (val) => {
  queryForm.value.pageSize = val;
  queryForm.value.page = 1;
  queryBrands();
};

// 当前页变化
const handleCurrentChange = (val) => {
  queryForm.value.page = val;
  queryBrands();
};

// 条件查询
const queryUser = () => {
  queryForm.value.page = 1; 
  queryBrands();
};

// 新增
const addHandler = () => {
  dialogTitle.value = '新增品牌';
  form.value = {
    id: '',
    name: '',
    sort: 0,
    createBy: '',
    updateBy: '',
    isDeleted:0
  };
  dialogVisible.value = true;
};

// 编辑
const editHandler = async (row) => {
  try {
    dialogTitle.value = '编辑品牌';
    const result = await selectBrandById(row.id);
    
    if (result && result.data) {
      form.value = { ...result.data };
      dialogVisible.value = true;
    } else {
      ElMessage.error('获取品牌详情失败');
    }
  } catch (error) {
    console.error('获取品牌详情失败:', error);
    ElMessage.error('获取品牌详情失败，请稍后重试');
  }
};

// 删除
const deleteHandler = async (row) => {
  try {
    await ElMessageBox.confirm(
      '确定要删除该品牌吗？',
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    );
    const result = await deleteBrandById(row.id);
    
    // 假设后端返回 code 为 200 表示成功
    if (result && result.code === 200) {
      ElMessage.success('删除成功');
      queryBrands();
    } else {
      ElMessage.error('删除失败');
    }
  } catch (error) {
    if (error === 'cancel') return; 
    console.error('删除品牌失败:', error);
    ElMessage.error('删除品牌失败，请稍后重试');
  }
};

// 保存（新增或编辑）
// 保存（新增或编辑）
const saveForm = async () => {
  try {
    if (!form.value.name) {
      ElMessage.warning('请输入品牌名称');
      return;
    }

    let result;
    if (form.value.id) {
      // 编辑操作
      result = await updateBrand(form.value);
    } else {
      // 新增操作
      result = await addBrand(form.value);
    }
    // 假设后端返回 code 为 200 表示成功
    if (result && result.code === 200) {
      ElMessage.success(form.value.id ? '更新成功' : '新增成功');
      dialogVisible.value = false;
      queryBrands();
    } else {
      ElMessage.error(form.value.id ? '更新失败' : '新增失败');
    }
  } catch (error) {
    console.error('保存品牌数据失败:', error);
    ElMessage.error('保存失败，请稍后重试');
  }
};

// 预加载
onMounted(() => {
  queryBrands();
});
</script>

<template>
  <!-- 查询表单 -->
  <el-form :model="formData" label-width="auto" :inline="true" style="margin-bottom: 16px;">
    <el-form-item label="品牌名称">
      <el-input v-model="formData.name" placeholder="请输入品牌名称" />
    </el-form-item>
    <el-form-item label="创建人">
      <el-input v-model="formData.createBy" placeholder="请输入创建人" />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="queryUser">查询</el-button>
      <el-button @click="formData = { name: '', createBy: '' }">重置</el-button>
    </el-form-item>
  </el-form>

  <!-- 操作按钮 -->
  <el-button type="primary" @click="addHandler" style="margin-bottom: 16px;">新增</el-button>

  <!-- 表格 -->
  <el-table :data="BrandData" style="width: 100%" border>
    <el-table-column prop="id" label="ID" align="center" width="80" />
    <el-table-column prop="name" label="品牌名字" align="center" width="180" />
    <el-table-column prop="sort" label="排序" align="center" width="80" />
    <el-table-column prop="createTime" label="创建时间" align="center" width="180" />
    <el-table-column prop="createBy" label="创建人账号" align="center" width="120" />
    <el-table-column prop="updateTime" label="修改时间" align="center" width="180" />
    <el-table-column prop="updateBy" label="修改人账号" align="center" width="120" />
    <el-table-column fixed="right" label="操作" min-width="120" align="center">
      <template #default="scope">
        <el-button link type="primary" size="small" @click="editHandler(scope.row)">
          编辑
        </el-button>
        <el-button link type="danger" size="small" @click="deleteHandler(scope.row)">
          删除
        </el-button>
      </template>
    </el-table-column>
  </el-table>

  <!-- 分页 -->
  <div class="demo-pagination-block" style="margin-top: 16px; text-align: right;">
    <el-pagination 
      v-model:current-page="queryForm.page" 
      v-model:page-size="queryForm.pageSize"
      :page-sizes="[5, 10, 15, 20]" 
      layout="total, sizes, prev, pager, next, jumper" 
      :total="queryForm.total"
      @size-change="handleSizeChange" 
      @current-change="handleCurrentChange" 
    />
  </div>

  <!-- 新增/编辑弹窗 -->
  <el-dialog v-model="dialogVisible" :title="dialogTitle" width="500px">
    <el-form :model="form" label-width="100px">
      <el-form-item label="品牌名称" prop="name" :rules="[{ required: true, message: '请输入品牌名称', trigger: 'blur' }]">
        <el-input v-model="form.name" placeholder="请输入品牌名称" />
      </el-form-item>
      <el-form-item label="排序" prop="sort">
        <el-input v-model.number="form.sort" placeholder="请输入排序号" type="number" />
      </el-form-item>
      <el-form-item label="创建人" v-if="!form.id">
        <el-input v-model="form.createBy" placeholder="请输入创建人" />
      </el-form-item>
      <el-form-item label="修改人" v-if="form.id">
        <el-input v-model="form.updateBy" placeholder="请输入修改人" />
      </el-form-item>
      <el-form-item label="是否删除" prop="isDeleted" style="display: none;">
        <el-input v-model="form.isDeleted" type="hidden" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="dialogVisible = false">取消</el-button>
      <el-button type="primary" @click="saveForm">确定</el-button>
    </template>
  </el-dialog>
</template>

<style scoped>
</style>